<template>
  <div class="shop-categories" id="shop-categories" ref="my_shop_categories">
    <HearderTop :isShowBoxShadow="isShowScreen"></HearderTop>

    <searchBox class="newClass" :backColor="isShowScreen" :way="false" :pageList="pageList">
      <!-- 选中筛选的数据 -->
      <div class="chose_list" v-if="!isShowScreen && filterCondition.length > 0">
        <ul>
          <li v-for="(item, index) in filterCondition" :key="index">{{ item.stastsName || item.bandName }}</li>
          <li @click="handelClickExpand">
            <span class="expand">展开</span>
            <el-icon v-if="isExpand">
              <ArrowDown />
            </el-icon>
            <el-icon v-else>
              <ArrowUp />
            </el-icon>
          </li>
        </ul>
      </div>
    </searchBox>

    <!-- 属性值筛选 -->
    <div
      class="filter-wrap"
      v-show="isShow"
      :style="{ top: !isShowScreen ? '140px' : '114px', padding: expandHistory ? 0 : '0 20px 0 20px' }"
    >
      <!-- 文字搜索 -->
      <attrFilter
        :filterData="filterData"
        @changeAttr="changeAttr"
        :expand="expand"
        @reset="reset"
        @updateList="handelUpdateList"
      >
        <template #select>
          <div style="margin-bottom: 20px">
            <div style="display: flex; flex-wrap: wrap">
              <div class="attr-item">
                <p style="color: #86909c; font-size: 16px">线上同款：</p>
                <div class="attr3 ml4">
                  <el-select
                    v-model="isOnlineEquivalent"
                    placeholder="请选择"
                    size="small"
                    clearable
                    style="min-width: 120px"
                    @change="onlineEquallyChange"
                  >
                    <el-option label="线上有同款" :value="1" />
                    <el-option label="线上无同款" :value="0" />
                  </el-select>
                </div>
              </div>
              <div class="attr-item">
                <p style="color: #86909c; font-size: 16px">是否有模型：</p>
                <div class="attr3 ml4">
                  <el-select
                    v-model="isModel"
                    placeholder="请选择"
                    size="small"
                    clearable
                    style="min-width: 120px"
                    @change="onlineEquallyChange"
                  >
                    <el-option label="有模型" :value="1" />
                    <el-option label="无模型" :value="0" />
                  </el-select>
                </div>
              </div>
              <div class="attr-item">
                <p style="color: #86909c; font-size: 16px">是否定制：</p>
                <div class="attr3 ml4">
                  <el-select
                    v-model="customType"
                    placeholder="请选择"
                    size="small"
                    clearable
                    style="min-width: 120px"
                    @change="onlineEquallyChange"
                  >
                    <el-option label="不可定制" :value="1" />
                    <el-option label="可定制" :value="2" />
                  </el-select>
                </div>
              </div>
            </div>
            <div style="display: flex; flex-wrap: wrap">
              <div class="attr-item">
                <p style="color: #86909c; font-size: 16px; flex-shrink: 0">定制类型：</p>
                <el-checkbox-group v-model="templateCustomTypeList" size="small">
                  <!-- 二级属性 -->
                  <div v-for="item in shopType" class="attr-wrap attr-only2" style="margin-top: 20px" :key="item.dictValue">
                    <el-checkbox
                      :label="item.dictLabel"
                      :value="item.dictValue"
                      :key="item.dictValue"
                      @change="onlineEquallyChange"
                    >
                      <template #default>
                        <p class="attr2">{{ item.dictLabel }}</p>
                        <img class="active-icon" src="@/assets/images/chose_icon.png" alt="" />
                      </template>
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>
            </div>
          </div>
        </template>
      </attrFilter>
    </div>

    <div class="box-width" style="height: 1100px">
      <banner :categoryId="postData.categoryId" class="shops"></banner>
      <!--      -->
      <div class="sort">
        <div class="sort-l">
          <div style="font-size: 16px">排序：</div>
          <div class="sort-box" v-for="(item, index) in sortList" @click="changeSort(item, index)" :key="index">
            <span>{{ item.label }}</span>
            <img v-if="!item.isAsc" :src="require('@/assets/images/asc.png')" />
            <img v-else :src="require('@/assets/images/desc.png')" />
          </div>
          <div class="sort_btn">
            <span>价格属性:</span>
            <ul>
              <li v-for="(sort_item, i) in sortLists" :key="i" :class="num == i ? 'active' : ''" @click="handelClickSortBtn(i)">
                {{ sort_item.name }}
                <img v-if="num == i" :src="imgUrl" alt="" />
              </li>
            </ul>
          </div>
        </div>
        <div class="sort-r">
          <div style="font-size: 16px">价格范围：</div>
          <el-input type="number" min="0" v-model.number="postData.minPrice" placeholder="请输入" @keyup.enter="handelPrice" />
          至
          <el-input
            class="ml10"
            min="0"
            type="number"
            v-model.number="postData.maxPrice"
            placeholder="请输入"
            @keyup.enter="handelPrice"
          />
          <!-- @blur="handelPrice" -->
        </div>
      </div>
      <!-- 商品列表 -->
      <template v-if="picList.length">
        <div class="box-shop">
          <!-- <div class="pic-box" v-for="(items, a) in picList" :key="a" @click="goDetails(items)" :class="{ empty: items.isEmpty }">
            <div class="top-box"><img :src="items.mainPicUrl" alt="" style="width: 100%; height: 100%; object-fit: cover" /></div>
            <div class="bottom-box" v-if="items.productAliasName != ''">
              <div class="s-text-a">{{ items.productAliasName }}</div>
              <div class="s-text-b">¥{{ items.businessLowestPrice }}</div>
            </div>
          </div> -->
          <div class="product_card" v-for="product in picList" :key="product.productId" @click="goDetails(product)">
            <img class="card_img" :src="product.mainPicUrl" />
            <div class="card_title">{{ product.productAliasName }}</div>
            <div class="card_price">¥{{ product.businessLowestPrice }}</div>
          </div>
        </div>
        <div class="demo-pagination-block">
          <div class="demonstration">共 {{ totalPage }}页</div>
          <el-pagination
            class="jzt-pagination"
            v-model:currentPage="postData.page"
            v-model:page-size="postData.size"
            :background="true"
            layout="prev, pager, next, jumper"
            :total="totals"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </template>
      <el-empty v-else description="暂无数据" />
    </div>
  </div>
</template>
<script setup></script>
<script>
import banner from "@/views/home//components/banner";
import HearderTop from "@/views/home/components/HearderTop";
import searchBox from "@/views/home/components/search";
import shopSelectStore from "@/store/modules/shopSelect";
import { shopHomePage } from "@/apis/shopCategories";
import { getProducts, queryStastsList } from "@/apis/search";
import attrFilter from "@/views/home/components/attrFilter.vue";
import checked from "@/assets/images/chose_icon.png";
import useCodeArrStore from "@/store/modules/select";

export default {
  components: { banner, HearderTop, searchBox, attrFilter },
  data() {
    return {
      templateCustomTypeList: [],
      shopType: useCodeArrStore().getDict("shop_template_custom_type"),
      sortLists: [{ name: "正价" }, { name: "特价" }],
      num: -1, //添加动态class属性
      imgUrl: checked,
      sortList: [
        { label: "销量", isAsc: false },
        { label: "价格", isAsc: false },
        { label: "新品", isAsc: false }
      ],
      valueInput1: "",
      pageList: {},
      isfull: 4,
      totalPage: 0,
      valueInput2: "",
      postData: {
        page: 1,
        size: 24,
        categoryId: 0,
        searchKey: "",
        sortType: 0,
        sortTypeValue: 0,
        minPrice: "",
        maxPrice: ""
      },
      totals: 0,
      screenWidth: 0,
      picList: [],
      collapseActive: "1",
      filterData: [], //属性筛选列表数据
      _filterVal: [], //选中的属性筛选项ids
      _filterVal3: [], //选中的3级属性筛选项ids
      isExpand: false, //是否展开
      expand: ["2"],
      domId: null,
      isShowScreen: true, //是否显示筛选框
      filterCondition: [], //过滤条件最后得到的数据
      expandHistory: false, //是否为点击展开的
      priceType: 0,
      isShow: true,
      isOnlineEquivalent: null, //筛选条件-线上同款
      isModel: null, //筛选条件-是否有模型
      customType: "" //是否定制 1-不可定制 2-可定制尺寸
    };
  },
  watch: {
    $route: {
      handler: async function (to, from) {
        // 路由变化时的处理逻辑
        this.postData.categoryId = this.$route.query.categoryId;
        await this.getPageData();
        this.getFilterData();
      },
      // 设置为深度监听
      deep: true,
      immediate: true
    }
  },
  created() {
    // this.postData.categoryId = this.$route.query.categoryId;
    // this.getPageData();
  },
  mounted() {
    // this.screenWidth = document.body.clientWidth;
    // window.onresize = () => {
    //   //屏幕尺寸变化就重新赋值
    //   return (() => {
    //     this.screenWidth = document.body.clientWidth;
    //   })();
    // };
    // this.getFilterData()
    // window.addEventListener("scroll", this.activationScroll);
    let domId = document.getElementById("designer-app");
    this.domId = domId;
    domId.addEventListener("scroll", this.activationScroll);
    //
    //   const shopId = document.getElementById("shop-categories");
    // shopId.style.height = window.innerHeight + 20 + "px";
  },
  computed: {},
  methods: {
    // 正价，特价点击事件
    handelClickSortBtn(index) {
      this.num = index;
      this.priceType = index + 1;
      this.getPageData();
    },
    // 获取筛选的条件
    handelUpdateList(item) {
      this.filterCondition = item;
    },
    // 滚动事件
    activationScroll(event) {
      // event.preventDefault();
      // ���动事件处理
      this.expandHistory = false;
      const scrollTop = event.target.scrollTop;
      if (scrollTop > 20) {
        this.isShow = false;
        this.isShowScreen = false;
        this.expand = [];
      } else if (scrollTop == 0) {
        this.isShowScreen = true;
        this.isShow = true;
        this.expand = ["2"];
      }
    },
    handelClickExpand() {
      this.isExpand = !this.isExpand;
      this.expandHistory = true;
      this.isShow = !this.isShow;
      if (this.isExpand) {
        this.expand = ["2"];
        this.domId.removeEventListener("scroll", this.activationScroll);
        setTimeout(() => {
          this.domId.addEventListener("scroll", this.activationScroll);
        }, 5000);
      } else {
        this.expand = [];
        this.domId.addEventListener("scroll", this.activationScroll);
      }
    },
    reset() {
      this.isModel = "";
      this.isOnlineEquivalent = "";
      this.customType = "";
      this._filterVal = [];
      this._filterVal3 = [];
      this._brandIds = [];
      const categoryId = this.postData.categoryId;
      this.templateCustomTypeList = [];
      this.postData = {
        page: 1,
        size: 24,
        categoryId: categoryId,
        searchKey: "",
        sortType: 0,
        sortTypeValue: 0,
        minPrice: "",
        maxPrice: ""
      };
      this.sortList = [
        { label: "销量", isAsc: false },
        { label: "价格", isAsc: false },
        { label: "新品", isAsc: false }
      ];
      this.num = -1;

      this.filterDataSubmit();
      this.getFilterData();
    },
    //属性筛选id改变时的回调
    changeAttr({ filterVal, filterVal3, brandIds }) {
      this._filterVal = filterVal;
      this._filterVal3 = filterVal3;
      this._brandIds = brandIds;
      this.filterDataSubmit(); //属性筛选接口请求
    },
    // 筛选条件-线上同款
    onlineEquallyChange() {
      this.filterDataSubmit();
    },
    filterDataSubmit(init = true) {
      const attrIds2 = this._filterVal.flat(); //选中的二级属性ids
      for (let ids2 of attrIds2) {
        const str = this._filterVal3.find(item => typeof item == "string" && item.includes(ids2));
        !str && this._filterVal3.push(ids2);
      }
      if (init) this.postData.page = 1;

      getProducts({
        ...this.postData,
        isOnlineEquivalent: this.isOnlineEquivalent,
        isModel: this.isModel,
        customType: this.customType,
        stastsIdsStr: this._filterVal3, //属性筛选ids
        brandIds: this._brandIds, //品牌id
        templateCustomTypeList: this.templateCustomTypeList
      }).then(res => {
        if (res.code === 200) {
          this.totalPage = res.data?.pages || [];
          this.totals = res.data?.total ?? 0;
          this.picList = res.data?.records || [];
          this.pageList = res.data || {};
        }
      });
    },
    getFilterData(imgSearchKey) {
      queryStastsList({
        // searchKey: '',
        categoryId: this.postData.categoryId
        // minPrice: Number(this.postData.minPrice),
        // maxPrice: Number(this.postData.maxPrice)
      }).then(res => {
        if (res.code === 200) {
          // 给需要渲染的child添加是否被选中属性
          res.data.map(it => {
            if (it.children?.length > 0) {
              it.children.map(it2 => {
                it2.checked = false;
                if (it2.children?.length > 0) {
                  it2.children.map(it3 => {
                    it3.checked = false;
                  });
                }
              });
            }
          });
          this.filterData = res.data || [];
        }
      });
    },
    goDetails(item) {
      shopSelectStore().setShopDetail(item);
      if (item.isEmpty) {
        return;
      }
      this.$router.push({
        path: "/shopDetail/index",
        query: {
          id: item.productId
        }
      });
    },
    getPageData() {
      shopHomePage({
        ...this.postData,
        priceType: this.priceType,
        stastsIdsStr: this._filterVal3, //属性筛选ids
        brandIds: this._brandIds //品牌id
      })
        .then(res => {
          const { data } = res;
          this.totalPage = data?.pages || [];
          this.totals = data?.total ?? 0;
          this.picList = data?.records || [];
          this.pageList = data || {};
        })
        .catch(err => {
          console.log(err);
        });
    },
    handleSizeChange() {
      this.getPageData();
    },
    handleCurrentChange() {
      this.getPageData();
    },
    changeSort(data, index) {
      if (this.postData.sortType !== index + 1) {
        this.postData.sortType = index + 1;
        this.sortList.forEach(item => {
          item.isAsc = false;
        });
      }
      data.isAsc = !data.isAsc;
      this.postData.sortTypeValue = this.postData.sortTypeValue === 0 ? 1 : 0;
      this.getPageData();
    },
    handelPrice() {
      if (!this.postData.maxPrice && !this.postData.minPrice) {
        this.getPageData();
        // this.getFilterData();
      } else {
        if (this.postData.maxPrice !== 0 && !this.postData.maxPrice) {
          return this.$message.error("请输入最大值");
        }
        if (this.postData.minPrice !== 0 && !this.postData.minPrice) {
          return this.$message.error("请输入最小值");
        }
        if (this.postData.maxPrice < this.postData.minPrice) {
          return this.$message.error("请输入正确的价格范围");
        }
        this.getPageData();
        // this.getFilterData();
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@use "@/assets/styles/mixin";

p,
h1 {
  margin: 0;
  padding: 0;
  font-weight: normal;
}

:deep(.reset_box) {
  margin-top: 20px;
}

:deep(.el-collapse-item__content) {
  margin-top: 10px;
}

:deep(.search-box) {
  // background-color: #fff;
}

.active {
  border: 1px solid #000;
}

.sort_btn {
  display: flex;
  align-items: center;

  ul {
    li {
      float: left;
      margin: 0 6px;
      box-shadow: 0px 3px 8px 0px rgba(0, 0, 0, 0.16);
      background-color: white;
      padding: 9px 16px;
      border-radius: 4px;
      cursor: pointer;
      position: relative;
      box-sizing: border-box;

      img {
        position: absolute;
        right: 0;
        bottom: -1px;
        width: 19px;
      }
    }
  }
}

.chose_list {
  margin-top: 100px;
  background-color: #fff;
  padding: 20px;
  overflow: hidden;
  position: fixed;
  top: -6px;
  width: 100%;
  z-index: 9;

  ul {
    display: flex;

    li {
      padding: 4px 10px;
      border: 1px dashed #ccc;
      margin: 0 10px 0 0;
      border-radius: 20px;
      color: #4e5969;
    }

    li:last-child {
      cursor: pointer;
      border: none;
      display: flex;
      align-items: center;
      padding: 0;

      .expand {
        margin: 0 6px 0 0;
      }
    }
  }
}

$gray: #f8fafb;

.filter-wrap {
  background-color: $gray;
  padding: 0px 20px 0 20px;
  position: sticky;
  top: 114px;
  z-index: 2;

  & > div {
    background-color: white;
    padding: 0 20px 20px 20px;
    border-radius: 10px;
    box-shadow: 4px 5px 16px 0px rgba(4, 19, 74, 0.05);
  }

  .img-serach-attr {
    display: flex;

    .left {
      width: 100px;
      height: 100px;
      position: relative;

      & > div {
        // position: absolute;
        // top:0;
        // bottom: 0;
        // left: 0;
        // right: 0;
      }

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }

  .attr-item {
    display: flex;
    align-items: center;
    margin-right: 50px;
  }

  :deep(.el-collapse-item__header) {
    font-size: 16px;
    color: #3d3d3d;
  }

  :deep(.el-collapse-item__wrap) {
    border-bottom: none;

    .el-collapse-item__content {
      padding-bottom: 0;
    }
  }
}

.demo-pagination-block {
  @include mixin.flex-center;
  padding: 20px 0;
  //margin-bottom: 20px;

  .demonstration {
    margin: 0 5px;
  }
}

.detail-top {
  height: 720px;
  margin: 135px 20px 0 20px;
  background-color: #ffffff;
  box-shadow: 4px 5px 16px 0 rgba(4, 19, 74, 0.04);
  border-radius: 10px;
}

.shops {
  margin-top: 134px !important;
}

.sort {
  @include mixin.flex-between;
  padding: 20px;
  font-size: 14px;

  .sort-l {
    @include mixin.flex-align;

    .sort-box {
      @include mixin.flex-center;
      width: 72px;
      height: 32px;
      margin-right: 10px;
      background-color: #ffffff;
      border-radius: 2px;
      border: 1px solid #dcdfe6;
      cursor: pointer;

      img {
        width: 16px;
        height: 16px;
        margin-left: 5px;
      }
    }
  }

  .sort-r {
    display: flex;
    align-items: center;

    :deep(.el-input__wrapper) {
      background-color: white !important;
    }

    :deep(.el-input) {
      width: 80px;
      margin-right: 10px;
      font-size: 14px;
    }
  }
}

.box-shop {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(289px, 1fr));
  gap: 20px;
  padding: 0 20px;
  justify-content: center;

  .product_card {
    position: relative;
    top: 0;
    height: 400px;
    text-align: center;
    background: #ffffff;
    box-shadow: 4px 5px 16px 0px rgba(4, 19, 74, 0.04);
    border-radius: 10px 10px 10px 10px;
    transition: all 0.1s ease-in-out;

    .card_img {
      width: 100%;
      height: 280px;
      border-radius: 10px;
    }

    .card_title {
      box-sizing: border-box;
      padding: 0 20px;
      margin-top: 26px;
      font-weight: 700;
      font-size: 16px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      color: #3d3d3d;
      line-height: 24px;
    }

    .card_price {
      font-family: din;
      margin-top: 10px;
      height: 24px;
      font-weight: 700;
      font-size: 16px;
      color: #4e5969;
      line-height: 24px;
    }
  }

  .product_card:hover {
    top: -10px;
    box-shadow: 4px 8px 16px 0px rgba(4, 54, 114, 0.15);
  }

  .pic-box {
    width: 100%;
    min-width: 289px;
    height: 400px;
    cursor: pointer;
    background-color: #ffffff;
    box-shadow: 4px 5px 16px 0 rgba(4, 19, 74, 0.04);
    border-radius: 10px;

    .top-box {
      margin: 0 auto;
      height: 250px;
      overflow: hidden;
      background-color: #ebebeb;
      box-shadow: 4px 0 4px 0 rgba(4, 19, 74, 0.1);
      border-radius: 10px;
    }

    .bottom-box {
      @include mixin.flex-center;
      flex-direction: column;

      .s-text-a {
        width: 80%;
        text-align: center;
        height: 24px;
        margin-top: 26px;
        font-weight: 700;
        font-size: 16px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #3d3d3d;
        margin-bottom: 8px;
        line-height: 24px;
      }

      .s-text-b {
        height: 24px;
        font-weight: 700;
        font-size: 16px;
        color: #4e5969;
        line-height: 24px;
      }
    }

    &.empty {
      background: #f8fafb;
      box-shadow: none;
      cursor: auto;

      .top-box {
        background: #f8fafb;
        box-shadow: none;
      }
    }
  }
}
</style>
